package itheima.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.common.contants.RedisKeyConstants;
import com.itheima.common.safe.AliyunSafeTemplate;
import com.itheima.question.pojo.Question;
import com.itheima.question.pojo.QuestionItem;
import com.xxl.job.core.handler.annotation.XxlJob;
import itheima.mapper.QuestionItemMapper;
import itheima.mapper.QuestionMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
@Slf4j
public class AuditTask {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionItemMapper questionItemMapper;

    @Autowired
    private AliyunSafeTemplate aliyunSafeTemplate;


    public AuditTask() {
    }

//    @Scheduled(cron = "0 0 2 * * ?")
    @XxlJob("auditQuestion")
    public void auditQuestion() {

        //1、查询redis中集合的内容
        Set<String> questionIds = redisTemplate.boundSetOps(RedisKeyConstants.AUDI_QUESTION).members();
        log.info("start question audit, questionIds is" + questionIds);
        if (questionIds != null && questionIds.size() > 0) {
            //2、遍历集合获取每一个题目的id，根据id查询题干和选项内容，最后进行审核
            for (String questionId : questionIds) {
                audit(questionId);
            }
        }

    }

    private void audit(String questionId) {
        StringBuilder content = new StringBuilder();  //builder线程不安全，buffer线程安全,存文本内容的
        List<String> urlList = new ArrayList<>(); //存储图片地址的

        //文本审核
        //根据题目id查询题目
        Question question = questionMapper.selectById(questionId);
        if (question == null) {
            return;
        }
        content.append(question.getSubject());

        if (question.getPicture() != null && question.getPicture().length() > 0) {
            urlList.add(question.getPicture());
        }

        //查询问题的选项
        QueryWrapper<QuestionItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("question_id", questionId);
        List<QuestionItem> questionItems = questionItemMapper.selectList(queryWrapper);
        if (questionItems != null && questionItems.size() > 0) {
            for (QuestionItem questionItem : questionItems) {
                content.append(questionItem.getContent());
                String picture = questionItem.getPicture();
                if (picture != null && picture.length() > 0) {
                    urlList.add(picture);
                }
            }
        }
        try {
            //1.题目的内容审核
            log.info("question content is" + content.toString());
            Map<String, String> contextResult = aliyunSafeTemplate.greenTextScan(content.toString());

            if (!"pass".equals(contextResult.get("suggestion"))) {
                return;
            }

            //2.题目的图片审核
            log.info("url list is" + urlList);

            if (urlList.size() > 0) {
                Map<String, String> urlResult = aliyunSafeTemplate.imageScan(urlList);

                if (!"pass".equals(urlResult.get("suggestion"))) {
                    return;
                }

            }
            //进一步操作，修改review_state 字段
            question.setReviewStatus("1");
            questionMapper.updateById(question);

            //TODO 审核之后，需要将该题目，【使用MQ做异步解耦合】导入到es索引库, 后面前端题目的搜索页面可以搜索到
            //方案1： 直接连接es索引库，通过es的api操作es索引库，实现数据的导入【强耦合】
            //方案2： 题目id作为一个消息，发送到MQ中【结束】    【后续编写，会有一个程序，单独运行，获取题目id，完成导入索引库的操作】
        } catch (Exception e) {
            e.printStackTrace();
            log.error("audit error!!");
        } finally {
            redisTemplate.delete(RedisKeyConstants.AUDI_QUESTION);
        }
    }

}